import Axios from 'axios';
import { MessageBox, Message } from 'element-ui';
import { getToken, getSiteId } from '@/utils/auth';
import store from '../store';

const baseURL = process.env.VUE_APP_BASE_API;

class httpRequest {
    constructor () {
        this.options = {
            method: '',
            url: ''
        };
        // 存储请求队列
        this.queue = {};
    }
    // 销毁请求实例
    destroy (url) {
        delete this.queue[url];
        const queue = Object.keys(this.queue);
        return queue.length;
    }
    // 请求拦截
    interceptors (instance, url) {
        // 添加请求拦截器
        instance.interceptors.request.use(config => {
            // config.headers[''] = 'web';
            if (store.getters.token) {
                config.headers['X-TULIANG-Session-Token'] = getToken();
                // config.params = Object.assign({}, config.params, { siteId: getSiteId() });
            }
            // Spin.show()
            // 在发送请求之前做些什么
            return config;
        }, error => {
            // 对请求错误做些什么
            return Promise.reject(error);
        });

        // 添加响应拦截器
        instance.interceptors.response.use((res) => {
            const {data} = res;
            if (res.headers && res.headers['']) {
                setToken(res.headers['']);
            }
            return data;
        }, (error) => {
            const msg = error.response.data.message;
            switch (error.response.status) {
            case 0:
                Message.error('服务器连接失败');
                break;
            case 400:
                Message.error(msg);
                break;
            case 401:
                MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    store.dispatch('LogOut').then(() => {
                        location.reload(); // 为了重新实例化vue-router对象 避免bug
                    });
                });
                break;
            case 403:
                Message.error('资源不可用');
                break;
            case 404:
                Message.error('资源不存在');
                break;
            case 500:
                Message.error(msg);
                break;
            }
            // 对响应错误做点什么
            return Promise.reject(error);
        });
    }
    // 创建实例
    create () {
        let conf = {
            baseURL: baseURL,
            // timeout: 2000,
            headers: {
                'Content-Type': 'application/json; charset=utf-8',
                Accept: 'application/json, text/plain, */*; charset=utf-8',
                Pragma: 'no-cache',
                'Cache-Control': 'no-cache'
            }
        };
        return Axios.create(conf);
    }
    // 合并请求实例
    mergeReqest (instances = []) {
        //
    }
    // 请求实例
    request (options) {
        var instance = this.create();
        this.interceptors(instance, options.url);
        options = Object.assign({}, options);
        this.queue[options.url] = instance;
        return instance(options);
    }
}
export default httpRequest;
